﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;

namespace M.Core.Utils
{
    public class HttpUtil
    {
        public static string HttpWebRestfulGet(string url, string param)
        {
            //param = param.IndexOf('?') > -1 ? (param) : ("?" + param);
            param = string.IsNullOrWhiteSpace(param)?string.Empty:("/" + param);

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + param);
            Encoding encoding = Encoding.UTF8;
            string responseData = String.Empty;
            req.Method = "GET";
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd();
                }
                return responseData;
            }
        }
        public static string HttpWebRequestGet(string url, string param)
        {
            param = string.IsNullOrWhiteSpace(param) ? string.Empty : (param.IndexOf('?') > -1 ? (param) : ("?" + param));

            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url + param);
            Encoding encoding = Encoding.UTF8;
            string responseData = String.Empty;
            req.Method = "GET";
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd();
                }
                return responseData;
            }
        }

        public static string HttpWebRequestPost(string url, string param)
        {
            HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
            Encoding encoding = Encoding.UTF8;
            byte[] byteArray = Encoding.ASCII.GetBytes(param);
            string responseData = String.Empty;
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            req.ContentLength = byteArray.Length;

            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(byteArray, 0, byteArray.Length);
            }
            using (HttpWebResponse response = (HttpWebResponse)req.GetResponse())
            {
                using (StreamReader reader = new StreamReader(response.GetResponseStream(), encoding))
                {
                    responseData = reader.ReadToEnd();
                }
                return responseData;
            }
        }
    }
}
